package cn.nkpro.elcube.components.financial.services

import cn.nkpro.elcube.co.NkAbstractCustomScriptObject
import cn.nkpro.elcube.co.spel.NkSpELInjection
import cn.nkpro.elcube.utils.MathUtils
import cn.nkpro.elcube.utils.xirr.Transaction
import cn.nkpro.elcube.utils.xirr.Xirr
import org.springframework.stereotype.Component

import java.util.stream.Collectors

@Component("SpELfinancial")
class NkSpELFinancial extends NkAbstractCustomScriptObject implements NkSpELInjection {

    @SuppressWarnings("unused")
    static Double xirr(Long loadDate, Double loanAmount, List<Map> income){

        if(loadDate && Double && income){

            try{
                def collect = income.stream()
                        .map({ item ->
                            return new Transaction(item.get("amount") as double, item.get("date") as long)
                        })
                        .collect(Collectors.toList())

                collect.add(0, new Transaction(-loanAmount, loadDate))

                Double rate = new Xirr(collect).xirr()

                return rate
            }catch(Exception ignored){

            }
        }

        return null
    }

    @SuppressWarnings("unused")
    static Double irr(Double loan, List<Double> income){
        if(loan && income){
            income.add(0, -loan)
            return MathUtils.irr(income,0.1d)
        }
        return null
    }
}
